package com.djz.tool.exception.handler;

import com.djz.tool.exception.base.BaseException;
import com.djz.tool.exception.category.BusinessException;
import com.djz.tool.utils.ResponseUtils;
import com.djz.tool.wrapper.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 业务异常处理器
 * @author djz
 */
@Slf4j
@Component
public class BusinessExceptionHandler implements ExceptionHandler<BaseException> {

    @Override
    public ResponseEntity<ResponseWrapper<Void>> handleException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        BusinessException businessException = (BusinessException) exception;
        String code = StringUtils.isNotBlank(businessException.getCode()) ? businessException.getCode() : "99999";
        String msg = StringUtils.isNotBlank(businessException.getDefaultMessage()) ? businessException.getDefaultMessage() : "系统未知异常！";

        log.error("全局捕获业务异常：[code]:{}, [msg]:{}", code, msg, exception);
        return ResponseEntity.status(HttpStatus.OK).header("Content-Type", "application/json;charset=UTF-8").body(new ResponseWrapper<Void>(Integer.parseInt(code), msg, null));
    }
}
